package blog

import (
	// "fmt"
	"github.com/astaxie/beego"
	"github.com/russross/blackfriday"
	"golang-blog/filter"
	"golang-blog/models"
)

const (
	msg    = "请检查您是否填写完整"
	layout = "T.Layout.tpl"
)

type TopicController struct {
	beego.Controller
}

// @router /topic/:url.html [get]
func (this *TopicController) Get() {
	url := this.Ctx.Input.Param(":url")
	//判断URL是否为空
	if len(url) == 0 {
		this.Abort("404")
	}
	//判断博文是否为空
	Topic := models.GetTopic(url)
	if Topic == nil {
		this.Abort("404") //设置404页面
	}
	this.Data["Topic"] = Topic
	this.Data["url"] = this.Ctx.Input.Param(":url")
	if filter.IsLogin(this.Ctx) {
		this.Data["User"] = true
	}
	this.TplNames = "topic.html"
}

// @router /new [get]
func (this *TopicController) GetNewTopicHtml() {
	this.Layout = layout
	this.TplNames = "newtopic.html"
}

// @router /new [post]
func (this *TopicController) NewTopic() {
	title := this.GetString("title")
	content := this.GetString("content")
	url := this.GetString("url")
	if len(title) == 0 || len(url) == 0 || len(content) == 0 {
		this.Data["msg"] = msg
		this.Data["title"] = title
		this.Data["url"] = url
		this.Data["content"] = content
		this.Layout = layout
		this.TplNames = "newtopic.html"
		return
	}
	content = string(blackfriday.MarkdownBasic([]byte(content)))
	if !models.AddTopic(url, title, content) {
		this.Data["msg"] = "数据库保存出错"
		this.Layout = layout
		this.TplNames = "newtopic.html"
		return
	}
	reurl := "/topic/" + url + ".html"
	this.Redirect(reurl, 302)
}

// @router /del/:tid [get]
func (this *TopicController) DelTopic() {
	tid := this.Ctx.Input.Param(":tid")
	err := models.DelTopic(tid)
	if !err {
		this.Data["msg"] = "删除文章出错"
		this.Data["Topic"] = models.GetTopicById(tid)
		this.TplNames = "topic.html"
		return
	}
	this.Redirect("/", 302)
}

// @router /modify/:tid [get]
func (this *TopicController) ModifyTopic() {
	tid := this.Ctx.Input.Param(":tid")
	this.Data["Topic"] = models.GetTopicById(tid)
	this.Layout = layout
	this.TplNames = "modify.html"
}

// @router /modify/:tid [post]
func (this *TopicController) ModifyTopicPost() {
	tid := this.Ctx.Input.Param(":tid")
	title := this.GetString("title")
	content := string(blackfriday.MarkdownBasic([]byte(this.GetString("content"))))
	url := this.GetString("url")
	models.ModifyTopic(tid, title, content, url)
	reurl := "/topic/" + url + ".html"
	this.Redirect(reurl, 302)
}
